<?php 	
	include('connect.php');
	header('Access-Control-Allow-Origin: *');
	header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
	header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE');

	// $content = 'Machine-made in China of 100% polyester, the Callie Shag Collection offers a series of stylish rugs in e ight beautiful color combinations.';
	//$tag = "to'";

	$content = $_POST['content'];
	$tag = $_POST['tag'];
	$tagList = [];
	$num = 0;

	$sql = 'select * from tags where content = "'.$content.'"';
	//当没有tag参数时，查询输入语句的tags
	if($tag == ''){
		$result = $db->query($sql);
		$rows = [];
		while($row = $result->fetch_array(MYSQLI_ASSOC)){
			$tagList[] = $row;
		}
	}else{
		$queryTags = 'select * from tag where tag = "'.$tag.'"';
		$result = $db->query($queryTags);
		if($result->num_rows == 0){
			$addTag = 'insert into tag (tag) values ("'.$tag.'")';
			$db->query($addTag);
		}
		
		$result = $db->query($sql);
		if($result->num_rows == 0){//第一次插入语句
			$addSentence = 'insert into tags (content,tag1) values ("'.$content.'","'.$tag.'")';
			$db->query($addSentence);

			$tagList = ['tag1'=>$tag];
			echo json_encode($tagList);
			exit;
		}

		if(!$result){
			echo "SQL错误";
			exit;	
		}

		$rows = [];
		while($row = $result->fetch_array(MYSQLI_ASSOC)){
			$rows[] = $row;
		}
		
		//获取非空标签
		$num = sizeof($rows[0])-3;
		$tagAll = array_slice($rows[0], 2, $num);
		$list = array_unique($tagAll);
		$iSNull = in_array('', $list);
		
		if($iSNull){
			$index = array_search('', $list);
			unset($list[$index]);
		}
		
		
		if(in_array($tag, $list)){
			$list['code'] = 2;//标签重复
			$tagList = $list;
			echo json_encode($tagList);
			exit;
		}

		if(sizeof($list) == 5){
			$tagList['code'] = 1;//标签数量达上限
			echo json_encode($tagList);
			exit;
		}

		$values = [];

		$sql1 = '';
		foreach ($list as $key => $value) {
			array_push($values, $value);
		}
		array_push($values, $tag);
		$count1= 5-sizeof($values);
		
		for($y=0;$y<$count1;$y++){
			array_push($values, '');
		}
		
		for($x=0;$x<5;$x++){
			if($x==4){
				$sql1 .= 'tag'.($x+1).'="'.$values[$x].'"';
			}else{
				$sql1 .= 'tag'.($x+1).'="'.$values[$x].'",';
			}
		}

		$sql = 'update tags set '.$sql1.' where content="'.$content.'"';
		$db->query($sql);

		$list['tag'.(sizeof($list)+1)] = $tag;
		$tagList = $list;
	}

	echo json_encode($tagList);
	
	



